package cn.edu.suda.catalina.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import cn.edu.suda.catalina.entity.Diary;

/**
 * Created by gzy on 2016/6/21.
 */

public class MSQLiteService {

    private MSQLiteOpenHelper msqLiteOpenHelper;
    private SQLiteDatabase mSQLiteDatabase;
    private ContentValues mContentValues;

    private String[] result_columns = new String[]{MSQLiteOpenHelper.TABLE_ID, MSQLiteOpenHelper.TABLE_TIME, MSQLiteOpenHelper.TABLE_DIARY};
    private String where = null;
    private String[] whereArgs = null;
    private String groupBy = null;
    private String having = null;
    private String orderBy = MSQLiteOpenHelper.TABLE_TIME + " desc";

    public MSQLiteService(Context context) {
        msqLiteOpenHelper = new MSQLiteOpenHelper(context, MSQLiteOpenHelper.DATABASE_NAME, null, MSQLiteOpenHelper.DATABASE_VERSION);
        mSQLiteDatabase = msqLiteOpenHelper.getWritableDatabase();
        mContentValues = new ContentValues();
    }

    public void insert(Diary diary) {

        setContentValues(diary);
        mSQLiteDatabase.insert(MSQLiteOpenHelper.DATABASE_TABLE, null, mContentValues);
        clearContentValues();

    }

    public List<Diary> getDiary() {

        return query();
    }

    private void setContentValues(Diary diary) {
        mContentValues.put(MSQLiteOpenHelper.TABLE_TIME, diary.getTime());
        mContentValues.put(MSQLiteOpenHelper.TABLE_DIARY, diary.getDiary());
    }

    private void clearContentValues() {
        mContentValues.clear();
    }

    private List<Diary> query() {
        Cursor cursor = mSQLiteDatabase.query(MSQLiteOpenHelper.DATABASE_TABLE, result_columns, where, whereArgs, groupBy, having, orderBy);
        List<Diary> mDiary = new ArrayList<>();
        while (cursor.moveToNext()) {
            Diary diary = new Diary();
            diary.setId(cursor.getInt(cursor.getColumnIndex(MSQLiteOpenHelper.TABLE_ID)));
            diary.setTime(cursor.getString(cursor.getColumnIndex(MSQLiteOpenHelper.TABLE_TIME)));
            diary.setDiary(cursor.getString(cursor.getColumnIndex(MSQLiteOpenHelper.TABLE_DIARY)));
            mDiary.add(diary);
        }
        cursor.close();
        return mDiary;
    }
}
